package org.microblog.service.impl;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.microblog.dao.UserDao;
import org.microblog.entity.User;
import org.microblog.service.UserService;
import org.microblog.util.SessionFatoryUtil;

import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    SqlSessionFactory sessionFactory = SessionFatoryUtil.sessionFactory;
    @Override
    public User findUser(String uId, String password) throws SQLException {
        SqlSession sqlSession = sessionFactory.openSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User tmp = userDao.findUser(uId, password);
        sqlSession.commit();
        sqlSession.close();
        return tmp;
    }

    @Override
    public int updateUser(User user) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession();
        UserDao userDao=sqlSession.getMapper(UserDao.class);
        int ret=userDao.updateUser(user);
        sqlSession.commit();
        sqlSession.close();
        return ret;
    }

    @Override
    public boolean findUserByid(String uId) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession(true);
        UserDao userDao=sqlSession.getMapper(UserDao.class);
        int ret=userDao.findUserByid(uId);
        sqlSession.commit();
        sqlSession.close();
        if (ret>0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public int register(User user) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession();
        UserDao userDao=sqlSession.getMapper(UserDao.class);
        int ret=userDao.register(user);
        sqlSession.commit();
        sqlSession.close();
        return ret;
    }
}
